/**
 * 
 */
package inz.model.patterns;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/** Set of Items that create one element of sequence */
public class Itemset
{
	private final Set<String> items = new HashSet<String>();

	/** Initializes itemset with single item
	 * @param singleItem first item of itemset */
	public Itemset(String singleItem)
	{
		items.add(singleItem);
	}

	/** Initializes itemset with given collection of items. Any duplicate items will be removed
	 * @param items collections of items that itemset will contain */
	public Itemset(Collection<String> items)
	{
		this.items.addAll(items);
	}

	/** @return the items */
	public Set<String> getItems()
	{
		return items;
	}

	/** adds new item to itemset */
	public void addItem(String newItem)
	{
		items.add(newItem);
	}

	/** checks if this itemset contains every element of given itemset */
	public boolean contains(Itemset other)
	{
		for (String item : other.getItems())
		{
			if (items.contains(item) == false)
			{
				return false;
			}
		}
		return true;
	}


	public void removeItems(Taxonomy taxonomy)
	{
		if (taxonomy == null)
		{
			return;
		}
		Set<String> toRemoveItems = new HashSet<String>();
		for (String itemString : items)
		{
			toRemoveItems.addAll(taxonomy.getAncestors(itemString));
		}

		Iterator<String> item = items.iterator();
		while (item.hasNext())
		{
			if (toRemoveItems.contains(item.next()))
			{
				item.remove();
			}
		}
	}

	/** @return number of items in itemset */
	public int getSize()
	{
		return items.size();
	}

	@Override
	public String toString()
	{
		StringBuffer result = new StringBuffer();
		int k = 0;
		for(String s : items) {
			k++;
			result.append(s);
			if (k < items.size())
			{
				result.append(",");
			}
		}
		return "(" + result + ")";
	}

	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + ((items == null) ? 0 : items.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj == null)
		{
			return false;
		}
		if (getClass() != obj.getClass())
		{
			return false;
		}
		Itemset other = (Itemset) obj;
		if (items == null)
		{
			if (other.items != null)
			{
				return false;
			}
		}
		else if (!items.equals(other.items))
		{
			return false;
		}
		return true;
	}
}
